package com.digitaleye.dpslite;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.StateListDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.widget.SimpleCursorAdapter;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.AdapterView.OnItemSelectedListener;
import com.downpayment.dps.R;



public class AddMoneyActivity extends Activity{
	
	AccountDBHelper accountDBHelper;
	TransferDBHelper transferDBHelper;
	DBHelper dbHelper;
	WebHelper webHelper;
	TipsDBHelper tipsDBHelper;
	
	Boolean editMode = false;
	
	Boolean firstTransfer = true;
	
	/** the position in the list view containing the selected Item **/
	/** used during edit Mode **/
	int checkPosition = 0;
	
	public static final int TRANSFER_FROM_DIALOG = 1;
	
	protected void onDestroy(){
		super.onDestroy();
		this.accountDBHelper.close();
		this.transferDBHelper.close();
	}
	
	@Override
	public void onStart(){
		super.onStart();
		//this.webHelper.authenticate("add_money");
	}

	
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		accountDBHelper = new AccountDBHelper(this);
		
		transferDBHelper = new TransferDBHelper(this);
		
		webHelper = new WebHelper(this);
		
		dbHelper = new DBHelper(this);
		
		tipsDBHelper = new TipsDBHelper(this);
		

		
		handleAccountNotCreated();

	
		
		
		
		
	}
	

	@Override
	protected Dialog onCreateDialog(int id) {

		AlertDialog.Builder builder = null;
		LayoutInflater inflater = null;
		
		switch (id) {
			
		case Constants.START_DATE_DIALOG:
			OnDateSetListener dateListener = new OnDateSetListener(){

				@Override
				public void onDateSet(DatePicker view, int year, int month, int day) {
					
					//change the starting date
					DecimalFormat formatter = new DecimalFormat("00");
					StringBuilder startDate = new StringBuilder().append(formatter.format(month+1))
							.append("/").append(formatter.format(day))
							.append("/").append(year);
					
					TextView startingText = (TextView) findViewById(R.id.transferStartingText);
					startingText.setText(startDate);
					
				}
				
			};
			
			Calendar c = Calendar.getInstance();
	        int year = c.get(Calendar.YEAR);
	        int month = c.get(Calendar.MONTH);
	        int day = c.get(Calendar.DAY_OF_MONTH);
	        
	        DatePickerDialog datePickerDialog = new DatePickerDialog(this, dateListener, year+1, month, day);
	        
			
			return datePickerDialog;
			
			
		case Constants.END_DATE_DIALOG:
			OnDateSetListener endDateListener = new OnDateSetListener(){

				@Override
				public void onDateSet(DatePicker view, int year, int month, int day) {
					
					//change the starting date
					DecimalFormat formatter = new DecimalFormat("00");
					StringBuilder startDate = new StringBuilder().append(formatter.format(month+1))
							.append("/").append(formatter.format(day))
							.append("/").append(year);
					
					TextView endingText = (TextView) findViewById(R.id.transferEndingText);
					endingText.setText(startDate);
					
				}
				
			};
			
			c = Calendar.getInstance();
	        int endYear = c.get(Calendar.YEAR) + 1;
	        int endMonth = c.get(Calendar.MONTH);
	        int endDay = c.get(Calendar.DAY_OF_MONTH);
	        
	        datePickerDialog = new DatePickerDialog(this, endDateListener, endYear, endMonth, endDay);
			
			return datePickerDialog;
		}
		return null;
	}
	
	
	
	/**
	 * if the user has an account, display add money information
	 */
	public void handleAccountNotCreated(){
		
		
		Runnable runnable = new Runnable() {

	        public void run() {
	        	AddMoneyActivity.this.initializeEnabledButtons();
	        	AddMoneyActivity.this.initializeDeleteLinks();
	        }
		};
		Handler handler =  new Handler();
		handler.postDelayed(runnable, 500);
		
		

		
		
		

		
		
	}
	
	
	/** if in linked account mode, display linked account options **/
	public void handleLinkedAccount(){
		
		//setContentView(R.layout.add_money_linked_account);

		
	}
	
	/**
	 * if user does not have an account, give the option to create or link to an existing one
	 */
	public void handleAccountCreated(){
		
		setContentView(R.layout.add_money);
		
		createSpinners();
		
		addRecurringTransfers();
		
		addSavingsTip();
		
		addButtonClickListeners();
		

			

	}

	
	@Override
    public void onWindowFocusChanged(boolean hasFocus) {
        // TODO Auto-generated method stub
        super.onWindowFocusChanged(hasFocus);
        initializeEnabledButtons();
        initializeDeleteLinks();
    }
	
	@Override
	public void onResume(){
		super.onResume();

		
	}


	/**
	 * adds the listeners to each button that is clickable
	 */
	public void addButtonClickListeners(){
		
		

		ImageView continueButton = (ImageView) findViewById(R.id.transferContinueBtn);
		
		continueButton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				
				
				/** handle the transfer **/
				
				confirmTransfer();
				
			}
			
		});
		
		continueButton.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				/** get the root element of the button view **/
		    	ImageView view = (ImageView) v;
		    	
		        if(event.getAction() == MotionEvent.ACTION_DOWN) {
		        	/** change the image button picture when clicked **/
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.continue_btn_clicked));
		        } else if (event.getAction() == MotionEvent.ACTION_UP) {
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.continue_btn));
		        }
		        else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
		        	view.setImageDrawable(v.getResources().getDrawable(R.drawable.continue_btn));
		        }
				return false;
			}
		});
		
		
		initializeEnabledButtons();
		
		initializeDatePicker();
		
	}
	
	public void initializeDatePicker(){
		
		// get the current date
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        
        NumberFormat formatter = new DecimalFormat("00");
        
        TextView startingText = (TextView) findViewById(R.id.transferStartingText);
        
        startingText.setText(new StringBuilder()
        	.append(formatter.format(month+1)).append("/")
        	.append(formatter.format(day)).append("/")
        	.append(formatter.format(year))
        );
        
        startingText.setClickable(true);
        startingText.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				showDialog(Constants.START_DATE_DIALOG);
				
			}
        	
        });
        
        TextView endingText = (TextView) findViewById(R.id.transferEndingText);
        
        endingText.setText(new StringBuilder()
        	.append(formatter.format(month+1)).append("/")
        	.append(formatter.format(day)).append("/")
        	.append(formatter.format(year+1))
        );
        
        endingText.setClickable(true);
        endingText.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				showDialog(Constants.END_DATE_DIALOG);
				
			}
        	
        });
		
	}
	
	/**
	 * add the list of recurring transfers to the view
	 */
	public void addRecurringTransfers(){

		Cursor transfersCursor = transferDBHelper.getTransfersAsCursor();
		
		LayoutInflater inflater = AddMoneyActivity.this.getLayoutInflater();
		
		LinearLayout recurringTransfersLayout = (LinearLayout) findViewById(R.id.recurringTransferLayoutPlaceholder);
		
		if(recurringTransfersLayout != null) recurringTransfersLayout.removeAllViews();
		
		
		/** if there are Recurring Transfers **/
		/** add recurring transfers view **/
		if(transfersCursor.moveToFirst()){
			
			
			
			recurringTransfersLayout.addView(inflater.inflate(R.layout.recurring_transfer_layout, recurringTransfersLayout, false));
			
			
			ListView transferList = (ListView) findViewById(R.id.recurringTransferList);
			transferList.setDivider(null);
			transferList.setDividerHeight(0);
			
			
			

			String[] fromColumns = {transferDBHelper.COLUMN_TRANSFER_AMOUNT, transferDBHelper.COLUMN_TRANSFER_FROM, transferDBHelper.COLUMN_TRANSFER_TO,
					transferDBHelper.COLUMN_TRANSFER_FREQUENCY, transferDBHelper.COLUMN_TRANSFER_ID, transferDBHelper.COLUMN_TRANSFER_STARTING};
			
			int[] toViews = { R.id.transferListItemAmount, R.id.transferListItemFromText, R.id.transferListItemToText, R.id.transferListItemTimeFrame,
					R.id.transferListItemID, R.id.transferListItemStarting};

			
			
			SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
			        R.layout.recurring_transfer_listitem, transfersCursor, fromColumns, toViews, 0);
			
			transferList.setAdapter(adapter);
			
			Utility.setListViewHeightBasedOnChildren(transferList);
		}

	}
	
	
	
	public void createFrequencySpinner(){
		
		Spinner frequencySpinner = (Spinner) findViewById(R.id.transferFrequencySpinner);
		
		
		if(frequencySpinner != null){
			// Create an ArrayAdapter using the string array and a default spinner layout
			ArrayAdapter<CharSequence> timeAdapter = ArrayAdapter.createFromResource(this,
			        R.array.transfer_frequency_array, R.layout.frequency_list_item);
			// Specify the layout to use when the list of choices appears
			timeAdapter.setDropDownViewResource(R.layout.frequency_dropdown_list_item);
			//Apply the adapter to the spinner
			frequencySpinner.setAdapter(timeAdapter);
			
			frequencySpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
	
				@Override
				public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
					// TODO Auto-generated method stub
					
					TableRow startingLayout = (TableRow) findViewById(R.id.transferStartingLayout);
					TableRow endingLayout = (TableRow) findViewById(R.id.transferEndingLayout);
					
					/** if "Once, Now" is NOT selected, display the starting box **/
					if(position == 1){
						startingLayout.setVisibility(View.VISIBLE);
						endingLayout.setVisibility(View.GONE);
					}
					else if(position != 0){
						
						startingLayout.setVisibility(View.VISIBLE);
						endingLayout.setVisibility(View.VISIBLE);
						
					}
					else{
						/** if Once, Now is selected, disable starting box **/
						startingLayout.setVisibility(View.GONE);
						endingLayout.setVisibility(View.GONE);
					}
					
				}
	
				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub
					
				}
				
			});
		}
		
		
	}
	
	/**
	 * removes scheduled transfer options from frequency spinner
	 */
	public void disableFrequencySpinner(){
		Spinner frequencySpinner = (Spinner) findViewById(R.id.transferFrequencySpinner);
		// Create an ArrayAdapter using the string array and a default spinner layout
		ArrayAdapter<CharSequence> timeAdapter = ArrayAdapter.createFromResource(this,
		        R.array.unscheduled_transfer_frequency_array, R.layout.frequency_list_item);
		// Specify the layout to use when the list of choices appears
		timeAdapter.setDropDownViewResource(R.layout.frequency_dropdown_list_item);
		//Apply the adapter to the spinner
		frequencySpinner.setAdapter(timeAdapter);
		
		frequencySpinner.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
				// TODO Auto-generated method stub
				
				TableRow startingLayout = (TableRow) findViewById(R.id.transferStartingLayout);
				TableRow endingLayout = (TableRow) findViewById(R.id.transferEndingLayout);
				
				/** if "Once, Now" is NOT selected, display the starting box **/
				if(position == 1){
					startingLayout.setVisibility(View.VISIBLE);
					endingLayout.setVisibility(View.GONE);
				}
				else if(position != 0){
					
					startingLayout.setVisibility(View.VISIBLE);
					endingLayout.setVisibility(View.VISIBLE);
					
				}
				else{
					/** if Once, Now is selected, disable starting box **/
					startingLayout.setVisibility(View.GONE);
					endingLayout.setVisibility(View.GONE);
				}
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
	}
	
	/**
	 * Creates the Spinners used for Scheduling a Transfer
	 */
	public void createSpinners(){
		
		
		Cursor accountsCursor = accountDBHelper.getAccountsAsCursor();
		
		String[] fromColumns = {accountDBHelper.COLUMN_ACCOUNT_NAME};
		int[] toViews = { R.id.account_list_item_text};

		
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
		        R.layout.account_list_item, accountsCursor, fromColumns, toViews, 0);
		
		
		/** From Account Spinner **/
		Spinner fromSpinner = (Spinner) findViewById(R.id.transferFromSpinner);
		// Apply the adapter to the spinner
		
		if(fromSpinner != null){
			fromSpinner.setAdapter(adapter);
			/*************************/
			
			
			
			fromSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
	
				@Override
				public void onItemSelected(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					
					if(view != null){
						
						TextView fromText = (TextView) view.findViewById(R.id.account_list_item_text);
						String from = fromText.getText().toString();
						
						//if selected item is FROM DPS account, disable scheduled transfers
						if(from.equalsIgnoreCase(AccountDBHelper.DPS_ACCOUNT_NAME)){
							/** disable frequency spinners **/
							disableFrequencySpinner();
						}
						else{
							createFrequencySpinner();
						}
						
					}
	
					
				}
	
				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub
					
				}
				
			});
		}
		
		/** To Account Spinner **/
		Spinner toSpinner = (Spinner) findViewById(R.id.transferToSpinner);
		
		if(toSpinner != null){
			toSpinner.setAdapter(adapter);
			
			/** automatically set the TO account to the DPS account **/
			for(int i = 0; i < accountsCursor.getCount(); i++){
				accountsCursor.moveToPosition(i);
				
				//default To SPinner location = DPS Account
				if(accountsCursor.getString(accountsCursor.getColumnIndex(accountDBHelper.COLUMN_ACCOUNT_NAME)).equals(accountDBHelper.DPS_ACCOUNT_NAME)){
					toSpinner.setSelection(i);
				}
				else{
					
					//Else, the default location is the last account in the cursor
					if(i == (accountsCursor.getCount()-1)){
						toSpinner.setSelection(i);
					}
					
				}
			}
		
		}
				
		/***********************/
		
		
		createFrequencySpinner();

	}
	
	
	
	
	public void handleDelete(){
		
		
		
		ListView transferList = (ListView) findViewById(R.id.recurringTransferList);
		
		
		/** get the ID of the selected Transfer **/
		TableRow row = (TableRow)transferList.getChildAt(checkPosition);
		FrameLayout frame = (FrameLayout)row.getChildAt(0);
		LinearLayout linear = (LinearLayout)frame.getChildAt(1);
		CheckBox check = (CheckBox)linear.getChildAt(0);
		TextView textID = (TextView) linear.getChildAt(1);
		
		int tid = Integer.parseInt((String) textID.getText());
		
		transferDBHelper.delete(tid);
		
		finish();
		
		Intent intent = new Intent(AddMoneyActivity.this, TabRoot.class);
		//Log.d("Main Activity", "Starting Mortgage Calc Activity");
		intent.putExtra("START_TAB", "add_money");
		AddMoneyActivity.this.startActivity(intent);
		
		
		
	}
	
	public void handleUpdate(){
		
		
		/** get views containing necesarry info **/
		Spinner frequencySpinner = (Spinner) findViewById(R.id.transferFrequencySpinner);
		EditText amountEditText = (EditText) findViewById(R.id.transferAmountValue);
		Spinner fromSpinner = (Spinner) findViewById(R.id.transferFromSpinner);
		Spinner toSpinner = (Spinner) findViewById(R.id.transferToSpinner);
		
		
		
		/** get the info from each view **/
		String frequency = frequencySpinner.getSelectedItem().toString();
		int amount = Integer.parseInt(amountEditText.getText().toString());
		
		String from = null;
		Cursor fromCursor = ((Cursor) fromSpinner.getSelectedItem());
		from = fromCursor.getString(fromCursor.getColumnIndex(accountDBHelper.COLUMN_ACCOUNT_NAME));

		String to = null;
		Cursor toCursor = ((Cursor) toSpinner.getSelectedItem());
		to = toCursor.getString(toCursor.getColumnIndex(accountDBHelper.COLUMN_ACCOUNT_NAME));

		
		/** if in edit mode , update the transfer, don't insert new one **/
		ListView transferList = (ListView) findViewById(R.id.recurringTransferList);
		
		/** get the ID of the selected Transfer **/
		TableRow row = (TableRow)transferList.getChildAt(checkPosition);
		FrameLayout frame = (FrameLayout)row.getChildAt(0);
		LinearLayout linear = (LinearLayout)frame.getChildAt(1);
		CheckBox check = (CheckBox)linear.getChildAt(0);
		TextView textID = (TextView) linear.getChildAt(1);
		
		int tid = Integer.parseInt((String) textID.getText());
		
		
		transferDBHelper.updateTransfer(tid, amount, from, to, frequency);
		
		//refresh the activity
		finish();
		
		Intent intent = new Intent(AddMoneyActivity.this, TabRoot.class);
		intent.putExtra("START_TAB", "add_money");
		AddMoneyActivity.this.startActivity(intent);
		
	}
	
	public void confirmTransfer(){
		
		/** get views containing necesarry info **/
		Spinner frequencySpinner = (Spinner) findViewById(R.id.transferFrequencySpinner);
		EditText amountEditText = (EditText) findViewById(R.id.transferAmountValue);
		Spinner fromSpinner = (Spinner) findViewById(R.id.transferFromSpinner);
		Spinner toSpinner = (Spinner) findViewById(R.id.transferToSpinner);
		TextView startingText = (TextView)findViewById(R.id.transferStartingText);
		TextView endingText = (TextView)findViewById(R.id.transferEndingText);
		
		/** get the info from each view **/
		String frequency = frequencySpinner.getSelectedItem().toString();
		
		
		int amount = -1;
		
		try{
			amount = Integer.parseInt(amountEditText.getText().toString());
		}
		catch(NumberFormatException e){
			
		}
		
		String from = null;
		Cursor fromCursor = ((Cursor) fromSpinner.getSelectedItem());
		from = fromCursor.getString(fromCursor.getColumnIndex(accountDBHelper.COLUMN_ACCOUNT_NAME));

		String to = null;
		Cursor toCursor = ((Cursor) toSpinner.getSelectedItem());
		to = toCursor.getString(toCursor.getColumnIndex(accountDBHelper.COLUMN_ACCOUNT_NAME));

		String starting = startingText.getText().toString();
		String ending = endingText.getText().toString();
		
		Date startingDate = null;
		Date endingDate = null;
		
		try {
			startingDate = new SimpleDateFormat("MM/dd/yyyy").parse(starting);
			endingDate = new SimpleDateFormat("MM/dd/yyyy").parse(ending);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		/** if a scheduled deposit, check if auto-transfers enabled **/
		if(!frequency.equalsIgnoreCase(getResources().getStringArray(R.array.transfer_frequency_array)[0])){
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
			boolean autoTransferEnabled = prefs.getBoolean("autoTransferPref", true);
			
			if(autoTransferEnabled == false){
				
				Toast.makeText(this, "Cannot Schedule a Transfer if auto-transfer is disabled. Change in settings", Toast.LENGTH_LONG).show();
				
				return;
			}
			
		}
		
		
		/** if not a one time deposit, and ending date is before the start date **/
		if(frequency.equalsIgnoreCase(getResources().getStringArray(R.array.transfer_frequency_array)[1])){
			endingDate = startingDate;
			ending = starting;
		}
		
		if(endingDate.before(startingDate)){
			Toast.makeText(this, "Starting Date must be after the ending date", Toast.LENGTH_LONG).show();
			return;
		}
		
		if(amount < 1){
			Toast.makeText(this, "Please enter a valid transfer amount", Toast.LENGTH_LONG).show();
			return;
		}
		
		if(from.equals(to)){
			Toast.makeText(this, "From and To accounts cannot be the same", Toast.LENGTH_LONG).show();
			return;
		}
		
		
		
		
		
		Intent intent = new Intent(AddMoneyActivity.this, TabRoot.class);
		
		/** put all the info in extras to confirm **/
		intent.putExtra("amount", amount);
		intent.putExtra("from", from);
		intent.putExtra("to", to);
		intent.putExtra("starting", starting);
		intent.putExtra("ending", ending);
		intent.putExtra("frequency", frequency);
		intent.putExtra("confirmTransfer", true);
		intent.putExtra("START_TAB", "add_money");
		
		this.startActivity(intent);
		
		
		

		
	}
	
	
	
	

	/**
	 * sets up the toggle on/off buttons for recurring transfers
	 */
	public void initializeEnabledButtons(){
		
		
		ListView transferList = (ListView) findViewById(R.id.recurringTransferList);

		if(transferList != null){
			for(int i = 0; i < transferList.getChildCount(); i++){
				
				/** set each check box as visible, add on click listeners **/
				TableRow row = (TableRow)transferList.getChildAt(i);
		
				final TextView textID = (TextView) row.findViewById(R.id.transferListItemID);
				final int tid = Integer.parseInt((String) textID.getText());
				final ToggleButton toggleButton = (ToggleButton)row.findViewById(R.id.toggleButton);
				
				StateListDrawable drawable = (StateListDrawable) toggleButton.getBackground();
				drawable.setLevel(5000);
				
				/** initialize state based on transfers.enabled **/
				if(transferDBHelper.getEnabled(tid) == 1){
					toggleButton.setChecked(true);
				}
				else toggleButton.setChecked(false);
				
				toggleButton.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View arg0) {

						
						if(toggleButton.isChecked()) transferDBHelper.setEnabled(tid, 1);
						else transferDBHelper.setEnabled(tid, 0);

					}
					
				});
			}
		}
		
	}
	
	
	/**
	 * adds the delete links for each recurring transfer
	 */
	public void initializeDeleteLinks(){
		
		
		ListView transferList = (ListView) findViewById(R.id.recurringTransferList);

		if(transferList != null){
			for(int i = 0; i < transferList.getChildCount(); i++){
				
				/** set each check box as visible, add on click listeners **/
				TableRow row = (TableRow)transferList.getChildAt(i);

				
				TextView deleteText = (TextView) row.findViewById(R.id.deleteTransferLink);
				
				TextView textID = (TextView) row.findViewById(R.id.transferListItemID);

				
				final int tid = Integer.parseInt(textID.getText().toString());
				
				deleteText.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View arg0) {
						
						
						
						AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
								AddMoneyActivity.this);
				 
				 
							// set dialog message
							alertDialogBuilder
								.setMessage("Would you like to Delete the transfer?")
								.setCancelable(false)
								.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,int id) {
										
										
										/** delete transfer **/
										transferDBHelper.delete(tid);
										
										/**remove it from the service **/
										startService();
										
										
										/** refresh activity **/
										Intent intent = new Intent(AddMoneyActivity.this, TabRoot.class);
								
										intent.putExtra("START_TAB", "add_money");
										AddMoneyActivity.this.startActivity(intent);
									}
								  })
								.setNegativeButton("No",new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,int id) {
										// if this button is clicked, just close
										// the dialog box and do nothing
										dialog.cancel();
									}
								});
				 
								// create alert dialog
								AlertDialog alertDialog = alertDialogBuilder.create();
				 
								// show it
								alertDialog.show();
						
					}
					
				});
			}
		}
		
	}

	/**
	 * enables/disables the check boxes for edit mode
	 */
	public void toggleCheckBox(){
		
		ListView transferList = (ListView) findViewById(R.id.recurringTransferList);
		
		
		if(AddMoneyActivity.this.editMode){
			
			
			for(int i = 0; i < transferList.getChildCount(); i++){
				
				/** set each check box as visible, add on click listeners **/
				TableRow row = (TableRow)transferList.getChildAt(i);
				FrameLayout frame = (FrameLayout)row.getChildAt(0);
				LinearLayout linear = (LinearLayout)frame.getChildAt(1);
				CheckBox check = (CheckBox)linear.getChildAt(0);
				final TextView textID = (TextView) linear.getChildAt(1);
				
				final int checkPosition = i;
				
				check.setVisibility(View.VISIBLE);
				
				check.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View arg0) {
						
						
						ListView transferList = (ListView) findViewById(R.id.recurringTransferList);
						
						/** uncheck all other boxes **/
						for(int i = 0; i < transferList.getChildCount(); i++){
							
							if(i != checkPosition){
								/** set each check box as visible, add on click listeners **/
								TableRow row = (TableRow)transferList.getChildAt(i);
								FrameLayout frame = (FrameLayout)row.getChildAt(0);
								LinearLayout linear = (LinearLayout)frame.getChildAt(1);
								CheckBox check = (CheckBox)linear.getChildAt(0);
								
								check.setChecked(false);
								
								
							}
							else{
								AddMoneyActivity.this.checkPosition = i;
							}
							
						}
						

						/** populate the form with this items information **/
						
						/** get views containing necesarry info **/
						Spinner frequencySpinner = (Spinner) findViewById(R.id.transferFrequencySpinner);
						EditText amountEditText = (EditText) findViewById(R.id.transferAmountValue);
						Spinner fromSpinner = (Spinner) findViewById(R.id.transferFromSpinner);
						Spinner toSpinner = (Spinner) findViewById(R.id.transferToSpinner);
						
						int transferID = Integer.parseInt((String) textID.getText());
						

						
						Cursor transfer = transferDBHelper.getTransferFromIDAsCursor(transferID);
						
						/**if there are results **/
						if(transfer.moveToFirst()){
							String frequency = transfer.getString(transfer.getColumnIndex(transferDBHelper.COLUMN_TRANSFER_FREQUENCY));
							String from_account = transfer.getString(transfer.getColumnIndex(transferDBHelper.COLUMN_TRANSFER_FROM));
							String to_account = transfer.getString(transfer.getColumnIndex(transferDBHelper.COLUMN_TRANSFER_TO));
							int amount = transfer.getInt(transfer.getColumnIndex(transferDBHelper.COLUMN_TRANSFER_AMOUNT));
							


							/** set the From Account **/
							for(int i = 0; i <= fromSpinner.getChildCount(); i++){
								Cursor cursor = (Cursor) fromSpinner.getItemAtPosition(i);
								if(cursor.getString(cursor.getColumnIndex(accountDBHelper.COLUMN_ACCOUNT_NAME)).equals(from_account)){
									fromSpinner.setSelection(i);
								}
							}
							
							/** set the TO account **/
							for(int i = 0; i <= toSpinner.getChildCount(); i++){
								
								Cursor cursor = (Cursor) toSpinner.getItemAtPosition(i);

								
								if(cursor.getString(cursor.getColumnIndex(accountDBHelper.COLUMN_ACCOUNT_NAME)).equals(to_account)){
									toSpinner.setSelection(i);
								}
							}
							
							/** set the Amount **/
							amountEditText.setText(String.valueOf(amount));
							
							/** set the Frequency **/
							for(int i = 0; i < frequencySpinner.getAdapter().getCount(); i++){
								
								String freq = (String) frequencySpinner.getItemAtPosition(i);

								
								if(freq.equals(frequency)){
									frequencySpinner.setSelection(i);
								}
							}
							
							
							/** set the focus on the new form info **/
							ScrollView sv = (ScrollView) findViewById(R.id.scrollView);
							
							TableLayout tl = (TableLayout) findViewById(R.id.scheduleTableTitle);
							
							int x = tl.getLeft();
							int y = tl.getTop();

							sv.scrollTo(x, y);
							
							
							
						}
						else{
						}
						
							
					}
					
				});
				
				
				
			}
		}
		
		else{
			for(int i = 0; i < transferList.getChildCount(); i++){
			
				/** set each check box as visible, add on click listeners **/
				TableRow row = (TableRow)transferList.getChildAt(i);
				FrameLayout frame = (FrameLayout)row.getChildAt(0);
				LinearLayout linear = (LinearLayout)frame.getChildAt(1);
				CheckBox check = (CheckBox)linear.getChildAt(0);
			
				check.setVisibility(View.GONE);
			}
		}
	}
	
	/** call start service to start or update it **/
	public void startService(){

		Intent serviceIntent = new Intent(this, AddMoneyService.class);
        startService(serviceIntent);
		
	}
	

	
	public void addSavingsTip(){
			
		
			TableLayout tipsTable;
			
			/** Insert Tips Table **/
			tipsTable = (TableLayout) findViewById(R.id.tipsTable);
			
			tipsTable.removeAllViews();
			
			LayoutInflater layoutInflater = (LayoutInflater) 
			        this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
			
			
			tipsTable.addView(layoutInflater.inflate(R.layout.tips_layout, tipsTable, false )); 
			/**********************/
			
			TextView titleText = (TextView) tipsTable.findViewById(R.id.tipTitle);
			
			TextView tipText = (TextView) tipsTable.findViewById(R.id.tipText);
			
			Tip tip = this.tipsDBHelper.getTip();
			
			if(tip != null){
				titleText.setText(tip.title);
				tipText.setText(tip.text);
			}

			

		}
	
	
	public void onGetAccountInfo(Account[] accounts){
		
		
		if(accounts == null || accounts[0] == null){
			
			showDialog(Constants.LOGIN_DIALOG);
		}
		else{
			this.accountDBHelper.deleteAll();
			for(Account account : accounts){
				this.accountDBHelper.addAccount(account);
				
				createSpinners();
			}
			
			
		}

	}

	

}
